package com.jlf.starter.logger.reactive;

import com.jlf.starter.logger.reactive.decorator.RequestDecorator;
import com.jlf.starter.logger.reactive.decorator.ResponseDecorator;
import com.jlf.starter.logger.reactive.entity.LogObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * 统一日志过滤器
 *
 * @author wujr
 * 2023/8/3
 * @version 1.0
 * 【变更历史】
 * [wujr 2023/8/3 1.0 新增]
 */
@Slf4j
@RequiredArgsConstructor
public class LoggingFilter implements WebFilter {
    @Override
    @NonNull
    public Mono<Void> filter(@NonNull ServerWebExchange exchange, WebFilterChain chain) {
        LogObject logObject = new LogObject(exchange);
        ServerHttpRequest logRequest = RequestDecorator.build(exchange, logObject);
        ServerHttpResponse logResponse = ResponseDecorator.build(exchange, logObject);
        ServerWebExchange wrapperExchange = exchange.mutate().request(logRequest).response(logResponse).build();
        return chain.filter(wrapperExchange);
    }
}
